package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.common.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import sun.rmi.runtime.Log;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author xiuer
 * @description 购物车增删改查操作
 * @create 2019/7/12 15:16
 */
@Service
@Slf4j
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String KEY_PREFIX = "ly:cart:uid:";


    public void addCart(Cart cart) {

        //获取当前用户信息
        String key = KEY_PREFIX + UserHolder.getUserInfo().getId();
        //获取hash对象,绑定当前key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        addOneCart(cart, hashOps);

    }

    /*新增一个商品到购物车*/
    private void addOneCart(Cart cart, BoundHashOperations<String, String, String> hashOps) {
        //获取商品id作为二层map的key
        String hashKey = cart.getSkuId().toString();
        //判断redsis中是否存在该key
        Boolean boo = hashOps.hasKey(hashKey);
        if (boo != null && boo) {
            //如果有该商品 ，则累加该商品
            Cart cacheCart = JsonUtils.toBean(hashOps.get(hashKey), Cart.class);
            cacheCart.setNum(cacheCart.getNum() + cart.getNum());
            //写回redis
            hashOps.put(hashKey, JsonUtils.toString(cacheCart));
        } else {
            //不存在则直接写入redis
            hashOps.put(hashKey, JsonUtils.toString(cart));
        }
    }

    public List<Cart> queryUserCart() {
        try {
            //获取当前用户信息
            String key = KEY_PREFIX + UserHolder.getUserInfo().getId();
            if (!redisTemplate.hasKey(key)) {
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
            //获取hash对象,绑定当前key
            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
            //获取map的所有值
            List<String> values = hashOps.values();
            if (CollectionUtils.isEmpty(values)) {
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
            return values.stream().map(str -> JsonUtils.toBean(str, Cart.class)).collect(Collectors.toList());
        } catch (LyException e) {
            log.error("购物车微服务 查询购物车失败 原因{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND, e);
        }
    }


    public void updateCart(String id, Integer num) {
        try {
            //获取当前用户信息
            String key = KEY_PREFIX + UserHolder.getUserInfo().getId();
            if (!redisTemplate.hasKey(key)) {
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
            String cartJson = hashOps.get(id);
            //获取hash对象,绑定当前key
            if (StringUtils.isEmpty(cartJson)) {
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
            Cart cacheCart = JsonUtils.toBean(cartJson, Cart.class);
            cacheCart.setNum(num);
            hashOps.put(id, JsonUtils.toString(cacheCart));
        } catch (LyException e) {
            log.error("【购物车微服务】 类名CartService方法updateCart 更新购物车失败，原因{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }

    }

    public void deleteCart(String id) {
        try {
            //获取当前用户信息
            String key = KEY_PREFIX + UserHolder.getUserInfo().getId();
            if (!redisTemplate.hasKey(key)) {
                throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
            }
            BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
            if (!hashOps.hasKey(id)) {
                throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
            }
            System.out.println(hashOps.delete(id));
            System.out.println("=====");
        } catch (LyException e) {
            log.error("【购物车微服务】 类名CartService方法updateCart 删除购物车失败，原因{}", e.getMessage(), e);
            throw new LyException(ExceptionEnum.DELETE_OPERATION_FAIL);
        }
    }

    /**
     * 批量新增购物车
     *
     * @param carts
     */
    public void addCarts(List<Cart> carts) {
        //获取当前用户信息
        String key = KEY_PREFIX + UserHolder.getUserInfo().getId();
        //获取hash对象,绑定当前key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        for (Cart cart : carts) {
            addOneCart(cart, hashOps);
        }
    }

    /**
     * 删除订单中（已购买）的商品
     *
     * @param MQmaps
     * @return
     */
    public void deleteCartBySkuIds(Map<String, Object> MQmaps) {
        //获取当前用户信息
        String key = KEY_PREFIX + MQmaps.get("uid");
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(key);
        List<Long> skuIds = (List<Long>) MQmaps.get("skuIds");
        for (Long skuId : skuIds) {
            hashOps.delete(skuId.toString());
        }
    }
}
